package app;

import java.net.URL;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;

import services.EventoServiceIntf;
import services.TipoServiceImpl;
import clases.Evento;
import constantes.Constantes;

public class DescargasFase2 {
	@Autowired
	EventoServiceIntf eventoService;
	
	@Autowired
	TipoServiceImpl tipoService;
	
	public void start(){
		
	try{
		List<Evento> eventList = eventoService.getEventosPendientes();
		for(Evento event : eventList){
				java.net.URL url = new URL(event.getUrl());
				org.jsoup.nodes.Document doc = Jsoup.parse(url,1000000);
				try{
					for(Element element : doc.getElementsByClass("event_body").get(0).getElementsByTag("P"))
						if(event.getDescripcion()!=null){
							event.setDescripcion(event.getDescripcion()+" / "+element.text());
						}else{
							event.setDescripcion(element.text());
						}
				if(event.getDescripcion().trim().isEmpty()){
					event.setDescripcion(Constantes.NO_EXISTE_DESC);
				}
				for(Element element : doc.getElementsByClass("event_data").get(0).getElementsByTag("P"))
					if(event.getSubtipo()!=null){
						event.setSubtipo(event.getSubtipo()+" / "+element.text());
					}else{
						event.setSubtipo(element.text());
					}
				
				}catch(Exception e){
					event.setDescripcion(Constantes.NO_EXISTE_DESC);
					System.out.println(url);
				}
				try{
					url = new URL(doc.getElementsByClass("map").get(0).getElementsByTag("a").attr("href"));
					doc = Jsoup.parse(url,1000000);
					String[] auxList = doc.getElementsByTag("script").get(1).toString().split("=");
					String lat = auxList[2].split(";")[0].trim();
					String lon = auxList[3].split(";")[0].trim();
					event.setCoordenadas(lat+"@"+lon);
				}catch(Exception e){
					event.setCoordenadas(Constantes.NO_EXISTE_COOR);
					System.out.println(url);
				}
				eventoService.persist(event);
		
		}
	System.out.println("END;");
	}catch (Exception e) {
			e.printStackTrace();
		}
	}
}
